﻿using Autofac;
using Autofac.Core;
using AutoFacLearn.Demo.Interface;
using Microsoft.Extensions.DependencyModel;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;


namespace AutoFacLearn.注册Demo.解析时传参
{
    public class Demo解析时传入对象
    {
        private static IContainer Container { get; set; }
        public void Demo(params Parameter[] parameters)
        {

            var builder = new ContainerBuilder();

            ///扫描所有的程序集
            List<CompilationLibrary> compilationLibrary = DependencyContext
                    .Default
                    .CompileLibraries
                    .Where(x => !x.Serviceable && x.Type != "package").ToList();

            foreach (var _compilation in compilationLibrary)
            {
                var list = AssemblyLoadContext.Default
                    .LoadFromAssemblyName(new AssemblyName(_compilation.Name));

                builder.RegisterAssemblyTypes(list)
                      .Where(t => t.Name.EndsWith("Domain") && !t.IsAbstract)
                      .AsImplementedInterfaces()
                      .PropertiesAutowired();
            }

            Container = builder.Build();
            using (var scope = Container.BeginLifetimeScope())
            {
                var component = scope.Resolve<IStudentDomain>(parameters);
                component.Test();
            }

        }
    }
}
